import { defineStore } from 'pinia'
import { setLanguage } from '../plugin/i18n'
import { storageDict } from '@/config/dict'
import { dict, getPlatFormConfigApi, getSettingConfigApi } from '@/api/common/index.js'
import { TIMEZONE_DICT } from '@/config/index'
import { useUserStore } from './user'
import { getUserRechageNewApi } from '@/api/account'
import { debounce } from 'lodash'
import { getCollect } from '@/api/trade/index'

import { _t18 } from '@/utils/public'

export const useMainStore = defineStore('main', {
  state: () => ({
    tradeStatus: 0,
    tradeFlag: '',
    isOption: 0,
    hasOption: false,
    hasCollectCoin: [],

    language: localStorage.getItem(storageDict.LANGUAGE),
    languageList: [],

    customerEmail: '',
    timezone: 'Asia/Hong_Kong',
    timezoneOffset: 8,
    timeFormat: 'MM/DD/YYYY',

    verificationCodeUrl: `${__config._BASE_API}/api/user/easyGenerateCode`,

    platFormConfig: {},
    settingConfig: {},
    userRechageMap: {}
  }),

  getters: {
    getSidebarList: (state) => state.settingConfig.APP_SIDEBAR_SETTING || [],
    getRechargeList: (state) => state.settingConfig.ASSET_COIN || [],
    getWithdrawList: (state) => state.settingConfig.WITHDRAWAL_CHANNEL_SETTING || [],
    getDefiList: (state) => state.settingConfig.DEFI_INCOME_SETTING || '',
    getHomeCoinList: (state) => state.settingConfig.HOME_COIN_SETTING || [],
    getLoginMethodList: (state) => state.settingConfig.LOGIN_REGIS_SETTING || '',
    getJinGangList: (state) => state.settingConfig.MIDDLE_MENU_SETTING || [],
    getAssetsTabList: (state) => state.settingConfig.TAB_SETTING || [],
    getPlayingList: (state) => state.settingConfig.PLAYING_SETTING || [],
    getTabbarList: (state) => state.settingConfig.BOTTOM_MENU_SETTING || [],
    getDownLoadList: (state) => state.settingConfig.DOWNLOAD_SETTING || [],

    getTradeHeaderList: (state) => {
      let tradeList = state.settingConfig.PLAYING_SETTING || []
      let tempList = []
      tradeList.forEach((item) => {
        if (item.name == '自选' && item.isOpen) {
          state.isOption = 1
          tempList.unshift({
            title: _t18('quote_optional'),
            componentName: 'Optional'
          })
        }
        if (item.name == '秒合约' && item.isOpen) {
          tempList.push({
            title: _t18('trade_tab6'),
            componentName: 'SecondContract',
            currentTab: 'secondContract'
          })
        }
        if (item.name == '币币交易' && item.isOpen) {
          tempList.push({
            title: _t18('trade_tab3'),
            componentName: 'BBTrading',
            currentTab: 'spot'
          })
        }
        if (item.name == 'U本位' && item.isOpen) {
          tempList.push({
            title: _t18('trade_tab5'),
            componentName: 'Ustandard',
            currentTab: 'contract'
          })
        }
      })
      return tempList
    },

    getLogoList: (state) => state.settingConfig.LOGO_SETTING || {},
    getISCode: (state) =>
      state.settingConfig.MARKET_URL == undefined
        ? true
        : state.settingConfig.MARKET_URL.h5Code,

    getVIPClass: (state) => state.settingConfig.VIP_LEVEL_SETTING || {},
    getVIPRule: (state) => state.settingConfig.VIP_DIRECTIONS_SETTING || {},

    getCustomerServiceList: (state) => {
      if (
        [
          'trustwallet',
          'coinmarketcap',
          'kabit',
          'etfinex',
          'ebc',
          'fx',
          'rxce',
          'gmtoin2',
          'math',
          'gatedefi'
        ].includes(__config._APP_ENV)
      ) {
        let script = document.createElement('script')
        script.type = 'text/javascript'
        script.src = `/platform/${__config._APP_ENV}/customer.min.js?${+new Date()}`
        document.body.append(script)
        let tempObj = { ...state.settingConfig.SUPPORT_STAFF_SETTING[0] }
        if (['rxce'].includes(__config._APP_ENV)) {
          tempObj.callback = () => {
            const userStore = useUserStore()
            ssq.push('setLoginInfo', {
              user_id: userStore.userInfo.user?.userId || '',
              user_name: userStore.userInfo.user?.userId || ''
            })
            ssq.push('chatOpen')
          }
        } else {
          tempObj.callback = () => {
            const userStore = useUserStore()
            let userId = userStore.userInfo.user?.userId || ''
            if (userId) {
              LiveChatWidget.call('set_customer_name', `UID_${userId}`)
            }
            LiveChatWidget.call('maximize')
          }
        }
        return [tempObj]
      } else if (
        ['bitfly', 'gmdoin', 'gmmoin', 'gmtoin', 'coinang', 'bkfcoin', 'hfm2'].includes(
          __config._APP_ENV
        )
      ) {
        let tempObj = { ...state.settingConfig.SUPPORT_STAFF_SETTING[0] }
        tempObj.getUrl = () => {
          const userStore = useUserStore()
          let userId = userStore.userInfo.user?.userId || ''
          return `${tempObj.url}&metadata={"name":"UID_${userId || 'temporary_' + +new Date()}"}`
        }
        return [tempObj]
      }
      return state.settingConfig.SUPPORT_STAFF_SETTING || []
    }
  },

  actions: {
    /** ✅ 获取平台配置（修复：返回 Promise 结果） */
    async getSettingConfig() {
      try {
        const res = await getSettingConfigApi()
        if (res.code === 200) {
          this.settingConfig = res.data
          this.setTimeZone()
          this.getLanguageList()
          this.hasOption = true
          return true // ✅ 成功返回 true
        } else {
          console.warn('getSettingConfig failed:', res.message)
          return false // ✅ 失败返回 false
        }
      } catch (error) {
        console.error('getSettingConfig error:', error)
        return false // ✅ 异常返回 false
      }
    },

    /** 获取用户收藏列表 */
    async getCollectCoinList() {
      const res = await getCollect()
      if (res.code == 200) {
        let list = []
        res.data.forEach((item) => {
          list.push(item.coin)
        })
        this.hasCollectCoin = list
      }
    },

    /** 防抖获取用户定制地址 */
    getUserRechageNewDebounce: debounce(
      async function (self) {
        let promiseList = []
        self.settingConfig.ASSET_COIN.map((elem) => {
          if (self.userRechageMap[elem.coinName] == undefined) {
            promiseList.push(getUserRechageNewApi(elem.coin, elem.coinName))
          }
        })
        if (promiseList.length) {
          Promise.all(promiseList).then((res) => {
            self.settingConfig.ASSET_COIN.forEach((elem, index) => {
              self.userRechageMap[elem.coinName] = res[index]['data'][elem.coinName] || ''
            })
          })
        }
      },
      5000,
      { leading: true, trailing: false }
    ),

    getUserRechageNew() {
      this.getUserRechageNewDebounce(this)
    },

    /** 设置时区 */
    setTimeZone() {
      const data = this.settingConfig.timeZone || ''
      const result = TIMEZONE_DICT.find((elem) => elem.offset == data.offSetValue) || null
      if (!result) {
        this.timezone = data.zoneId
        this.timezoneOffset = data.offSetValue
      } else {
        this.timezone = result.timezone
        this.timezoneOffset = data.offset
      }
    },

    /** ✅ 获取平台动态配置（保持一致返回 true/false） */
    async getPlatFormConfig() {
      try {
        const res = await getPlatFormConfigApi()
        const dynamicCode = res.data
        const dynamicFunction = new Function(dynamicCode)
        this.platFormConfig = dynamicFunction()
        return true
      } catch (error) {
        console.error('getPlatFormConfig error:', error)
        return false
      }
    },

    /** 设置语言 */
    setLanguage(language) {
      if (this.language != language) {
        this.language = language
        localStorage.setItem(storageDict.LANGUAGE, language)
        setLanguage(language)
      }
    },

    /** 获取语言列表 */
    getLanguageList() {
      this.languageList = this.settingConfig.t_app_language || []
    },

    /** 设置交易tabbar状态 */
    setTradeStatus(tradeStatus) {
      this.tradeStatus = tradeStatus
    },
    setTradeFlag(tradeFlag) {
      this.tradeFlag = tradeFlag
    }
  },

  /** ✅ 开启持久化 */
  persist: {
    paths: ['settingConfig']
  }
})
